import Taro, { Component, setNavigationBarTitle } from '@tarojs/taro';
import { View, ScrollView, Video, Image } from '@tarojs/components';
import './index.scss';
import { set as setGlobalData, get as getGlobalData } from '../../../utils/globalData';
import { shareList, claimCard, cardDetail, getUserCardCount } from '../../../services/electronicCard';
import { getSessionKey, decryptData, register, getUserInfo, update } from '../../../services/user';
import NavigationBar from '../../../components/navigationBar/index';
import { fullImgUrl, timeFormat, formatTimeDifference } from '../../../utils/utils';
import CardScrollArrow from '../electronic-lp/img/card_scroll_arrow.gif';
import CardShareBtn from '../electronic-lp/img/card_share_btn.png';
import CardCustomerPhone from '../electronic-lp/img/card_customer_phone.png';
import CardJoinPhone from '../electronic-lp/img/card_join_phone.png';
import CardClaimSuccess from '../electronic-lp/img/card_claim_success.png';
import CardClaimToDetail from '../electronic-lp/img/card_calim_to_detail.png';
import TabBar from '../../../components/tab-bar/index';
import Home from '../../../static/home/home2.png';

export default class Index extends Component {

  config = {
    navigationBarTitleText: '领取礼券'
  }

  state = {
    screenWidth: wx.getSystemInfoSync().screenWidth,
    screenHeight: wx.getSystemInfoSync().screenHeight,
    isScrolling: false,
    content: null,
    navigationBarHeight: Taro.getStorageSync('navigationBarHeight'),
    userInfo: Taro.getStorageSync('userInfo') || null,
    statusS: 4,
    list: [],
    btnStype: '',
    scrollPageStype: '',
    height: 0,
    card_id: 0,
    initiator_id: 0,
    isPlaying: false,
    isShowCardCliamSuccess: false,
    isShowCardCliamFail: false,
    cardDeadline: '',
    diffTime: '',
    diffContent: '',
  }
  timer = null; // 用于延迟取消虚化效果的计时器

  componentWillMount() {
    if (this.state.userInfo === null) {
      const delay = 3000; // 3秒
      const timer = setTimeout(() => {
        // 等待3秒，等待接口完成用户信息获取后，重新赋值一次用户信息
        this.setState({'userInfo': Taro.getStorageSync('userInfo')})
        this.dealCardDetail();
      }, delay);
      // 清除定时器以防止内存泄漏
      return () => {
        clearTimeout(timer);
      };
    }
  }

  componentDidMount() {
    this.dealCardDetail();

  }
  componentWillReceiveProps(nextProps, nextContext) { }
  componentWillUnmount() { }
  componentDidShow() {
    console.log('componentDidShow start')
    shareList().then(res => {
      console.log('componentDidShow set list start')
      let temp = res.list;
      Taro.setStorageSync('shareList', temp);
      this.setState({
        list: temp
      });
      console.log('componentDidShow set list end')
    })
    console.log('componentDidShow end')
  }
  componentDidHide() { }
  componentDidCatchError() { }
  componentDidNotFound() { }

  callCustomerPhone() {
    Taro.makePhoneCall({
      phoneNumber: '4008-921-221'
    })
  }

  dealCardDetail() {
    console.log(this.$router.params);
    let { card_id, initiator_id } = this.$router.params; // 假设路由参数中有 id 和 name
    // 如果有参数，先存起来，以防止刷新页面后没有数据
    if (card_id && initiator_id) {
      Taro.setStorageSync('electronic_card_claim_param', this.$router.params)
    } else {
      let electronic_card_claim_param = Taro.getStorageSync('electronic_card_claim_param')
      card_id = electronic_card_claim_param.card_id
      initiator_id = electronic_card_claim_param.initiator_id
    }

    this.state.card_id = card_id;
    this.state.initiator_id = initiator_id;

    let share_time = 0;
    let start_time = (new Date()).getTime() / 1000;
    cardDetail({
      card_id: card_id
    }).then(res => {
      share_time = res.share_time;
      if (start_time <= share_time + 3600 * 72) {
        // 时效内，未领取
        // 不为撤销状态
        if (res.share_status != 3) {
          setInterval(() => {
            let diffTime = formatTimeDifference((new Date()).getTime() / 1000, share_time + 3600 * 72)
            this.setState({ diffContent: "请在" + diffTime + "内领取" })
            // this.setState({ diffTime: diffTime });
          }, 1000);
        } else {
          // 撤销
          if (this.state.userInfo.id == initiator_id) {
            // 发卡人：分享人 = 当前用户
            this.setState({ diffContent: '已退回' })
          } else {
            // 领卡人
            this.setState({ diffContent: '已被领取' })
          }
        }
      } else {
        // 超时未领取
        if (this.state.userInfo.id == initiator_id) {
          // 发卡人：分享人 = 当前用户
          this.setState({ diffContent: '超过72小时未领取, 已退回您的卡包' })
        } else {
          // 领卡人
          this.setState({ diffContent: '超过72小时未领取, 已过期' })
        }
      }
      // 时效内，已领取
      if (res.share_status === 0) {
        this.setState({ diffContent: '已领取' })
      }
      // 状态是分享中，但是发卡人和卡持有人不一致，直接显示已领取
      if (res.share_status === 1 && res.convert_id == initiator_id) {
        this.setState({ diffContent: '已领取' })
      }
    })
  }

  callPhone() {
    Taro.makePhoneCall({
      phoneNumber: '189-6857-5998'
    })
  }

  collectCard() {
    const userInfo = Taro.getStorageSync('userInfo');
    if (!userInfo) {
      Taro.showToast({
        title: '用户还未登录，请先登录',
        icon: 'none'
      })
    }

    // 先拿到用户的基本信息，再领取卡券
    if (userInfo.nickname === '微信用户') {
      let id = userInfo.id;
      let data = {
        id: id
      }
      wx.getUserProfile({
        desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: (res) => {
          console.log(res)
          data.nickname = res.userInfo.nickName;
          data.avatar = res.userInfo.avatarUrl
          update(data).then((res) => {
            Taro.setStorageSync('userInfo', res.user);

            // 领取卡券
            this.claimCard();
          })
        }
      })
    } else {
      // 领取卡券
      this.claimCard();
    }
  }

  claimCard() {
    const { card_id, initiator_id } = this.state;
    if (card_id === 0 || initiator_id === 0) {
      Taro.showToast({
        title: '领取异常，请重新领取',
        icon: 'none'
      });
    }

    claimCard({
      card_id: card_id,
      initiator_id: initiator_id,
    }).then(res => {
      if (res == 204) {
        this.setState({ isShowCardCliamFail: true })
      } else {
        this.setState({ cardDeadline: timeFormat(parseInt(res.deadline_time, 10), 'yyyy.MM.dd') })
        this.setState({ isShowCardCliamSuccess: true })
      }
    }).catch((err) => {
      if (err) {
        Taro.showToast({
          title: err.data,
          icon: 'none'
        })
      }
    })
  }
  goCardsInfo() {
    Taro.redirectTo({
      url: '/subPackageWork/pages/electronic-card/index'
    });
  }

  onPageScroll() {
    // console.log('滚起来')
    // 滚动时设置 isScrolling 为 true，开启虚化效果
    this.setState({ isScrolling: true });
    // 清除之前的计时器
    clearTimeout(this.timer);

    // 在停止滚动后500ms恢复原样，取消虚化效果
    this.timer = setTimeout(() => {
      // console.log('停下来')
      this.setState({ isScrolling: false });
    }, 500);

  }

  onScrollToLower() {
    console.log('下拉加载更多');
  }
  handleVideoPlay(id) {
    this.videoContext = Taro.createVideoContext(id);
    const { isPlaying } = this.state;
    if (isPlaying) {
      // 暂停视频
      this.videoContext.pause();
    } else {
      // 播放视频
      this.videoContext.play();
    }
    // 切换播放状态
    this.setState({
      isPlaying: !isPlaying,
    });
  }

  render() {
    const { list, diffContent, isScrolling, isPlaying, screenWidth, screenHeight, isShowCardCliamSuccess, isShowCardCliamFail, cardDeadline } = this.state;
    return (
      <View className="customized" style={`margin-top: ${navigationBarHeight}`}>
        <NavigationBar text='领取礼券' type="home" backIcon={Home} ref={this.menuBarRef} />
        {(isShowCardCliamSuccess || isShowCardCliamFail) && <View className='card_claim_shadow'></View>}
        <View className='content'>
          <Image className='btn-stype-2' src={CardShareBtn} onClick={this.claimCard} />
          {/* {diffTime ? <Text className='btn-stype-3'>请在{diffTime}内领取</Text> : <Text className='btn-stype-3'>超过72小时未领取，已过期</Text>} */}
          {diffContent && <Text className='btn-stype-3'>{diffContent}</Text>}
          {isShowCardCliamSuccess &&
            <View className='claim_success'>
              <Image className='card_claim_bg' src={CardClaimSuccess}></Image>
              <View className='card_claim_h1'>领取成功</View>
              <View className='card_claim_des'>中鹿岛品鉴券有效期至{cardDeadline}</View>
              <Image className='card_claim_btn' src={CardClaimToDetail} onClick={this.goCardsInfo}></Image>
            </View>
          }
          {isShowCardCliamFail &&
            <View className='claim_success'>
              <Image className='card_claim_bg' src={CardClaimSuccess}></Image>
              <View className='card_claim_h2'>
                <Text style='display:block'>已放入您卡包</Text>
                <Text style='display:block'>不能重复领取哦~</Text>
              </View>
              <Image className='card_claim_btn' src={CardClaimToDetail} onClick={this.goCardsInfo}></Image>
            </View>
          }

          {screenHeight > 800 ?
            <Image className='btn-card-phone' style='top: 40%;' src={CardCustomerPhone} onClick={this.callCustomerPhone} />
            : <Image className='btn-card-phone' style='top: 35%;' src={CardCustomerPhone} onClick={this.callCustomerPhone} />
          }
          <Image className='btn-card-phone' style='top: 55%;' src={CardJoinPhone} onClick={this.callPhone} />
          <ScrollView
            className='scroll_view'
            scrollY
            scrollWithAnimation
            onScrollToLower={this.onScrollToLower}
          >
            {
              list.map(record => (
                <View className="item">
                  {record.type === 0 ? (
                    <Image className='img' src={`${fullImgUrl(record.image_url)}`} mode="widthFix" />
                  ) : (
                    <View className='video_container'>
                      <Video className='video'
                        style={`width: ${screenWidth}px; height: ${screenWidth / 1.67}px;`}
                        id={`videoPlayer${record.id}`}
                        autoplay={isPlaying}
                        controls={false} // 不显示默认控制条
                        showCenterPlayBtn={false} // 不显示中央播放按钮
                        showPlayBtn={false} // 不显示播放按钮
                        showProgress={false} // 显示进度条
                        showFullscreenBtn={false} // 不显示全屏按钮
                        poster={`${fullImgUrl(record.image_url)}`}
                        objectFit='fill'
                        src={record.video_url}
                        onClick={() => this.handleVideoPlay(`videoPlayer${record.id}`)}
                      />
                    </View>
                  )}
                </View>
              )
              )
            }
          </ScrollView>
          {!isScrolling && <Image className='scroll-page-2' src={CardScrollArrow} />}
        </View>
        <View className="tabBar" >
          <TabBar statusS={this.state.statusS}></TabBar>
        </View>
      </View>
    );
  }
}
